import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Alert, Col, Form, Row, Select, Tooltip, Modal, message } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import { getCurrentUser } from '@/utils/authority';
import OrderAreaRadioGroup from '../../components/OrderAreaRadioGroup1';
import OrderNumberCount from '../../components/OrderNumberCount';
import { queryWarehouseList, paoExpressKvOp, batchSetPacketOp } from '../../../../services';
import { useState, useEffect, useMemo, useRef } from 'react';
import { find } from 'lodash';

const { Option } = Select;

/** 批量设置跑量订单 */
function SetRunVolumeModal(props) {
  const [form] = Form.useForm();

  const [warehouseList, setWarehouseList] = useState([]);
  const [expressList, setExpressList] = useState([]);
  const [warehouseSelect, setSelected] = useState({});

  const [loading, setLoading]=useState(false);
  const [showNumber, setShowNumber] = useState({});
  const filterIds = useRef(undefined);

  const { orderList, searchForm, selectKeys } = props;

  const currentUser = useMemo(()=>{
    return getCurrentUser() || {};
 }, [])

 const disabled = useMemo(()=>{
   return !Object.keys(warehouseSelect)?.length;
 }, [warehouseSelect])

  //基础信息获取
  useEffect(() => {
    getWarehouseList();//发货仓列表
  }, [])

  useEffect(()=>{
   if(Object.keys(warehouseSelect)?.length){
    form.setFieldsValue({ baseExpressId: null })
    const { id, uuid } = warehouseSelect;
    const bool =  (filterIds.current || selectKeys).some(item=>{
      const obj = find(orderList, ['id', item]);
      return !obj.jdPlatformData?.homeDelivery;
    })
    getExpressList({
      warehouseId: id,
      sendMethod: currentUser.uuid == uuid ? 'ZIFA' : 'DAIFA',
			isUpDoor: bool ? 0 : 1
    });
   }
  },[warehouseSelect])

   //发货仓列表数据
   const getWarehouseList = async () => {
    const { success, data = [] } = await queryWarehouseList();
    if (success) {
      setWarehouseList(data);
    }
  }

   //快递列表
   const getExpressList = async (params) => {
    const { success, data = [] } = await paoExpressKvOp(params);
    if (success) {
      setExpressList(data);
    }
  }

  //修改仓库下拉
  const handleChangeWarehouse = (e) => {
    const obj = find(warehouseList, ['id', e]);
    if(obj){
      setSelected(obj);
    }
  }

  const closeAndRefresh = (delay) => {
    setLoading(true);
    setTimeout(()=>{
      setLoading(false);
      props.handleOk?.();
      props.handleCancel?.();
    }, 1000 * delay)
  }

  function handleOk() {
    if(!(showNumber?.[10] + showNumber?.[30])){
      return message.info('待审核或异常订单数量为0，无可处理的订单')
    }
    form.validateFields().then(async ({ warehouseId, baseExpressId })=>{
      setLoading(true);
      const { msg, success, data } = await batchSetPacketOp({
        warehouseId,
        orderIds: filterIds.current || selectKeys,
        logisticsId: baseExpressId,
        logisticsUuid: find(expressList, ['baseExpressId', baseExpressId])?.uuid
      });
      setLoading(false);
      if(success){
        if(data?.msg){
          Modal.info({
            centered: true,
            title: '设跑量提示',
            content: data.msg,
            onOk(){
              closeAndRefresh(3);
            }
          });
        }else{
          message.success(msg);
          closeAndRefresh(4);
        }
      }
    })
  }

  const orderAreaRadioProps = {
    searchForm, 
    selectKeys,
    orderList,
    title: '仅限待审核、异常状态订单',
    states: [10, 30],
    otherRulesFunc(obj){
      return !obj.runVolume
    },
    updateShowNumer(obj, ids){
      filterIds.current = ids;
      setShowNumber(obj);
      setSelected({});
      form.setFieldsValue({ warehouseId: null, baseExpressId: null})
    } 
  }

  return (
    <CommonModal title={{ title: '批量设置跑量订单' }} open={true} width="540px" onOk={handleOk} onCancel={props.handleCancel}>
      <Alert
        showIcon
        message={
          <Typography as="s1">
            <Typography useBold as="s1">
              自发仓：
            </Typography>
            设为跑量订单后，会自动读取商品管理设置的默认跑量商品生成跑量订单 <br />
            <Typography useBold as="s1">
              代发仓：
            </Typography>
            设为跑量订单后，订单商品会修改为跑量商品+跑量包装，请谨慎选择自己所需要的订单操作！
          </Typography>
        }
      />
      <CommonForm
        formProps={{
          form,
        }}
        columns={[
          {
            name: 'radio-group',
            slot: <OrderAreaRadioGroup wrapStyle={{ marginTop: 16 }} {...orderAreaRadioProps} />,
          },
          {
            block: (
              <OrderNumberCount
                data={[
                  { label: '待审核', value: showNumber[10], type: 'warning' },
                  { label: '异常', value: showNumber[30], type: 'error' },
                ]}
              />
            ),
          },
          {
            block: (
              <Row style={{ marginTop: 24 }} gutter={14}>
                <Col span={12}>
                  <Form.Item name="warehouseId" rules={[{required:'true', message: '请选择发货仓'}]}>
                    <Select placeholder="请选择发货仓" onChange={handleChangeWarehouse}>
                      { warehouseList.map((d) => (
                          <Option key={d.id} value={d.id} label={d.warehouseName}>
                            <Tooltip title={d.warehouseName}>{d.warehouseName}</Tooltip>
                          </Option>
                        ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name="baseExpressId" rules={[{required:'true', message: '请选择快递'}]}>
                    <Select placeholder={disabled? "请先选择发货仓" : "请选择快递"} disabled={disabled}>
                    { expressList.map((d) => (
                          <Option key={d.baseExpressId} value={d.baseExpressId} label={d.baseExpressName}>
                            <Tooltip title={d.baseExpressId}>{d.baseExpressName}</Tooltip>
                          </Option>
                        ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            ),
          },
        ]}
      ></CommonForm>
      <CommonLoading loading={loading} />
    </CommonModal>
  );
}

export default SetRunVolumeModal;
